package com.example.testlxr9096.itemActivity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.testlxr9096.R;
import com.example.testlxr9096.adapter.TestRecordAdapter;
import com.example.testlxr9096.bean.TestRecord;
import com.example.testlxr9096.database.AppDatabase;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class TestRecordActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private TestRecordAdapter adapter;
    private Button btnExport, btnDelete;

    private     List<TestRecord> testRecords;

    private ProgressDialog progressDialog;

    private static  final int REQUEST_CODE = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_record);
//        initPermission();

        testRecords = new ArrayList<>();
        btnExport = findViewById(R.id.btn_export);
        btnDelete = findViewById(R.id.btn_delete);

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

         Thread thread = new Thread(new Runnable() {
             @Override
             public void run() {
                 testRecords =   AppDatabase.getDatabase(TestRecordActivity.this).testRecordDao().getAllTestRecords();
                 if (checkArray()){
                     for (int i = 0; i < testRecords.size(); i++) {
                         testRecords.get(i).setId(i+1);

                     }
                 }

                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         if (checkArray()){
                             adapter = new TestRecordAdapter(testRecords);
                             recyclerView.setAdapter(adapter);
                             adapter.notifyDataSetChanged();
                         }



                     }
                 });
             }
         });
         thread.start();
        btnExport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exportToExcel();
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteAllRecords();
            }
        });



//         testRecords.add(new TestRecord(1,"2","3","4","5","6"));


    }

    public boolean checkArray(){
        if (testRecords==null||testRecords.size()==0){

            return false;
        }

        return true;
    };

    public void initPermission(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
        }
    }
    private void deleteAllRecords() {
        if (testRecords==null||testRecords.size()==0){
            Toast.makeText(TestRecordActivity.this, "测试记录为空", Toast.LENGTH_LONG).show();

            return;
        }
        new MaterialAlertDialogBuilder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除所有记录吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (testRecords!=null&&testRecords.size()!=0) {
                                    AppDatabase.getDatabase(TestRecordActivity.this).testRecordDao().deleteAllTestRecords();
                                    AppDatabase.getDatabase(TestRecordActivity.this).getOpenHelper().getWritableDatabase().execSQL("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'test_record_database'");


                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (testRecords!=null&&testRecords.size()!=0) {
                                            testRecords.clear();
                                            adapter.notifyDataSetChanged();
                                        }

                                    }
                                });
                            }
                        }).start();
                        // 删除所有记录



                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了权限，可以进行存储操作
//                exportToExcel();
            } else {
                // 用户拒绝了权限，提示用户权限被拒绝
                Toast.makeText(this, "存储权限被拒绝，无法导出Excel文件", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void exportToExcel() {
        if (testRecords==null||testRecords.size()==0){
            Toast.makeText(TestRecordActivity.this, "测试记录为空", Toast.LENGTH_LONG).show();

            return;
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在导出...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                   if (checkArray()){
                       createExcelFile(testRecords);
                   }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void createExcelFile(List<TestRecord> testRecords) {
        try {
            File dir = new File(Environment.getExternalStoragePublicDirectory(""), "1070测试记录");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    Log.e("TestRecordActivity", "Failed to create directory");
                    return;
                }
            }
            // 创建 Excel 文件的代码


            File file = new File(dir, "测试记录_" + System.currentTimeMillis() + ".xls");
            WritableWorkbook workbook = Workbook.createWorkbook(file);
            WritableSheet sheet = workbook.createSheet("测试记录",0);
            Label label = new Label(0,0, "ID");
            sheet.addCell(label);
            label = new Label(1,0, "日期");
            sheet.addCell(label);
            label = new Label(2,0, "类型");
            sheet.addCell(label);
            label = new Label(3,0, "名称");
            sheet.addCell(label);
            label = new Label(4,0, "错误信息");
            sheet.addCell(label);
            label = new Label(5,0, "状态");
            sheet.addCell(label);

            // 添加数据
            for (int i =0; i < testRecords.size(); i++) {
                TestRecord record = testRecords.get(i);
                label = new Label(0, i +1, String.valueOf(record.getId()));
                sheet.addCell(label);
                label = new Label(1, i +1, record.getDate());
                sheet.addCell(label);
                label = new Label(2, i +1, record.getType());
                sheet.addCell(label);
                label = new Label(3, i +1, record.getName());
                sheet.addCell(label);
                label = new Label(4, i +1, record.getErrorInfo());
                sheet.addCell(label);
                label = new Label(5, i +1, record.getState());
                sheet.addCell(label);
            }


            // 添加表头和数据

            workbook.write();
            workbook.close();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                    Toast.makeText(TestRecordActivity.this, "导出完成，文件路径：" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                    Toast.makeText(TestRecordActivity.this, "导出失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

}
